package br.com.android.financas.watcher;

import java.text.NumberFormat;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class CurrencyWatcher implements TextWatcher {

	private NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
	private EditText campo;

	public CurrencyWatcher(EditText campo) {
		this.campo=campo;
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
			campo.removeTextChangedListener(this);

			String cleanString=s.toString().replaceAll("\\D", "");

			if(cleanString.startsWith("0"))
			{
				cleanString=cleanString.substring(1);
			}

			if(cleanString.length()>1){
				String decimal=cleanString.substring(cleanString.length()-2);
				String inteira=cleanString.substring(0, cleanString.length()-2);
				cleanString=inteira+"."+decimal;
			}else{
				cleanString="0.0"+cleanString;
			}


			double price;
			try {
				price = Double.parseDouble(cleanString);
			} catch (java.lang.NumberFormatException e) {
				price = 0;
			}


			String formated = currencyFormat.format(price);

			campo.setText(formated);
			campo.setSelection(campo.getText().length(), campo.getText().length());

			campo.addTextChangedListener(this);
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void afterTextChanged(Editable s) {
	}

}
